/*
 * BiTreeXmlHelper.c
 *
 *  Created on: 2011-5-6
 *      Author: william nie
 */
#include"BiTreeXmlHelper.h"

/*
 * This method is used to create the BiTree recursively. It will return
 * the number of BTNodes it created.
 */
int CreateBiTreeFromXml(BTNode **treeNode, xmlNodePtr xmlNode){
	static int numOfNode = 0;
	xmlNodePtr leftXmlChild = NULL;
	xmlNodePtr rightXmlChild = NULL;
	if(xmlNode!=NULL&&xmlNode->children!=NULL){
		leftXmlChild = xmlNode->children;
		rightXmlChild = leftXmlChild->next;
	}

	if(xmlNode!=NULL){
		(*treeNode) = (BTNode*)malloc(sizeof(BTNode));

		xmlChar *valueStr = xmlGetProp(xmlNode, BAD_CAST "value");
		int valueInt = atoi(valueStr);
		(*treeNode)->data = valueInt;
		numOfNode ++;

		CreateBiTreeFromXml(&((*treeNode)->lchild),leftXmlChild);
		CreateBiTreeFromXml(&((*treeNode)->rchild),rightXmlChild);

	} else {
		*treeNode = NULL;
	}

	return numOfNode;
}

BiTree* LoadXmlBiTree(){
	BiTree *biTree = (BiTree*) malloc(sizeof(BiTree));

	XmlBiTree xmlBiTree = (XmlBiTree) malloc(sizeof(XmlBiTree));

	xmlKeepBlanksDefault(0);
	xmlBiTree->doc = xmlReadFile("file:///./BiTree.xml", "UTF-8", XML_PARSE_RECOVER);

	if (xmlBiTree->doc == NULL) {
		fprintf(stderr, "CAN'T OPEN XML SOURCE FILE!");
		fflush(stdin);
		getchar();
		exit(1);
	}

	xmlBiTree->curNode = xmlBiTree->root = xmlDocGetRootElement(xmlBiTree->doc);

	if (xmlBiTree->root == NULL) {
		fprintf(stderr, "THERE'S NO ROOT IN THIS FILE!");
		fflush(stdin);
		getchar();
		exit(1);
	}

	if (xmlStrcmp(xmlBiTree->root->name, BAD_CAST "root") != 0) {
		fprintf(stderr,"FILE'S ROOT WITH WRONG NAME:%s",xmlBiTree->root->name);
		fflush(stdin);
		getchar();
		exit(1);
	}

	biTree->nodnum = CreateBiTreeFromXml(&(biTree->root), xmlBiTree->root);
	biTree->treesize = biTree->nodnum * sizeof(BiTree);

	return biTree;
}

Status SaveXmlBiTree(BiTree* biTree) {

	return OK;
}
